package com.tank.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.tank.bean.MailValid;
import com.tank.bean.User;
import com.tank.core.TankModel;
import com.tank.dao.MailDAO;
import com.tank.dao.UserDAO;
import com.tank.service.MailService;
import com.tank.util.MailUtil;
import com.tank.vo.RetVo;

@Service("mailService")
public class MailServiceImpl implements MailService {
	@Autowired
	@Qualifier("mailDao")
	MailDAO dao;

	@Autowired
	@Qualifier("userDao")
	UserDAO udao;

	public void registerUser(User user) {
		System.out.println(user.getId());
		MailValid mv = new MailValid();
		mv.setAuthor(user);
		mv.setAction(MailValid.VALID_REG);
		mv.setUuid(UUID.randomUUID().toString());
		mv.setPubtime(new Date());
		mv.setValid(false);

		dao.save(mv);

		try {
			MailUtil.registerUser(user, mv);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public TankModel resetForm(User user) {
		TankModel tm=TankModel.newInstance();
		List<User> us = udao.findUserByNameOrMail(user);
		if (us == null  || us.isEmpty()) {
			tm.setSuccess(false);
			tm.setMessage("邮箱不存在!");
			return tm;
		}
		user = us.get(0);
		
		
		
		MailValid mv = new MailValid();
		mv.setAuthor(user);
		mv.setAction(MailValid.VALID_FIND);
		mv.setUuid(UUID.randomUUID().toString());
		mv.setPubtime(new Date());
		mv.setValid(false);

		dao.save(mv);

		try {
			MailUtil.resetValid(user, mv);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		tm.setMessage("邮箱验证已经发送，请查收");
		return tm;

	}

	public MailValid findMailValid(MailValid mv) {
		if(mv== null) return null;
		return dao.findByIdAndUUID(mv.getId(), mv.getAction());
	}




	public TankModel regValid(MailValid mv) {
		TankModel tm = TankModel.newInstance();
		tm.setMessage("邮箱验证成功！<a href=\"login\" target=\"blank\">登录</a>");
		
		
		User user = mv.getAuthor();
		user.setValid(true);
		udao.valildMail(user);
		
		
		
		return tm;
	}

	public TankModel resetValid(MailValid mv) {
		TankModel tm = TankModel.newInstance();
		
		User user = mv.getAuthor();
		String pass = UUID.randomUUID().toString().substring(3, 9);
		user.setPass(pass);
		udao.randomPass(user);
		
		
		tm.setMessage("请先记下临时密码：<font color=red><b>"+pass+"</b></font>"
				+ "<a href=\"login?user.name="+user.getName()+"&user.pass="+user.getPass()+"\" target=\"blank\" style=\"float:right;\"><用它登录></a>");
	
	
		return tm;
	}

}
